package leetcode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Problem22 {
    public static void main(String[] args) {
        Problem22 pp = new Problem22();
        List<String> res = pp.generateParenthesis(2);
        for (String r : res) {
            System.out.println(r);
        }
    }

    public List<String> generateParenthesis(int n) {
        List<String> resList = new ArrayList<>();
        backtracking(0, 0, n, new StringBuilder(), resList);
        return resList;
    }

    public void backtracking(int left, int right, int n, StringBuilder part, List<String> resList) {
        if (left + right == 2 * n) {
            resList.add(part.toString());
            return;
        }
        if (left < n) {
            part.append("(");
            backtracking(left + 1, right, n, part, resList);
            part.deleteCharAt(part.length() - 1);
        }
        if (right < left) {
            part.append(")");
            backtracking(left, right + 1, n, part, resList);
            part.deleteCharAt(part.length() - 1);
        }
    }
}
